<?php

namespace app\supply\logic;
use app\common\library\Excel;
use app\order\logic\OrderLogic;
use app\supply\logic\BasicLogic;
use think\facade\Db;
use DateTime;
use app\order\logic\OrderReportSkuLogic;
use app\purchase\logic\PlanSuggestLogic;
class SupplySaleLogic extends BasicLogic
{

    /**
     * @desc    供应商sku销量列表
     * @date    2024/7/30
     * @author  luckyXiong
     */
    public function get_list($params=[]){
        //实时查询
        $limit         = $params['limit'] ?? 10;
        $date          = $params['date'] ??'';
        $supply_id     = $params['supply_id'] ?? "";
        $customDate    = $params['customDate'] ?? 0;
        $groupId       = $params['groupId'] ?? '';
        $tel           = $params['tel'] ?? '';
        $where = [];
        //供应商;2024-10-21
        if($groupId == 18){
            $supply_info   =  Config('Logisticskey.supply_info');
            $supply_id     =  $supply_info[$tel]??'';
        }

        if($customDate){
            switch ($customDate) {
                case '1':
                    //实时
                    $yesterday = date('Y-m-d', time() - timezone());
                    $midnightYesterday = strtotime($yesterday . ' 00:00:00');
                    $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
                    $where[]  = ['c.createtime', '>=', $midnightYesterday];
                    $where[]  = ['c.createtime', '<=', $endOfYesterday];
                    $date = $yesterday;
                    break;
                case '2':
                    $yesterday = date('Y-m-d', strtotime('-1 day') - timezone());
                    $midnightYesterday = strtotime($yesterday . ' 00:00:00');
                    $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
                    $where[]  = ['c.createtime', '>=', $midnightYesterday];
                    $where[]  = ['c.createtime', '<=', $endOfYesterday];
                    $date = $yesterday;
                    break;
                case '3':
                    $yesterday    = strtotime(date('Y-m-d', time() - timezone()));
                    $yesterdayEnd = strtotime(date('Y-m-d', strtotime('-6 day') - timezone()));
                    $where[] = ['c.createtime', '<=', $yesterday];
                    $where[] = ['c.createtime', '>=', $yesterdayEnd];
                    $date = date('Y-m-d',$yesterdayEnd) ."到".date('Y-m-d 23:59:59',$yesterday) ;
                    break;
                default:
                    $yesterday = date('Y-m-d', strtotime('-1 day') - timezone());
                    $midnightYesterday = strtotime($yesterday . ' 00:00:00');
                    $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
                    $where[]  = ['c.createtime', '>=', $midnightYesterday];
                    $where[]  = ['c.createtime', '<=', $endOfYesterday];
                    $date     = $yesterday;
            }
        }else{
            if (!empty($date)) {
                $where[] = ['c.createtime', '>=', strtotime($date['0'])];
                $where[] = ['c.createtime', '<=', strtotime($date['1']) + 3600*24-1];
                $date = $date['0'] ."到".date('Y-m-d 23:59:59', strtotime($date['1']));
            }else{
                $yesterday = date('Y-m-d', strtotime('-1 day') - timezone());
                $midnightYesterday = strtotime($yesterday . ' 00:00:00');
                $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
                $where[]  = ['c.createtime', '>=', $midnightYesterday];
                $where[]  = ['c.createtime', '<=', $endOfYesterday];
                $date     = $yesterday;
            }
        }
        if ($supply_id) {
            $map   = [];
            $map[] = ['supply_id','=',$supply_id];
            //获取供应商对应的spu数据;
            $spus_info  = Db::name('supply_info')->where($map)->column('spu');
            if($spus_info){
                $where[] = ['a.spu', 'in', $spus_info];
            }else{
                $where[] = ['a.spu', 'in', []];
            }
        }

        $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

        $list = Db::name('order_skuinfo')
            ->field('
                sum(a.realcount) as skuquantity,
                a.spu
            ')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->where($where)
            ->group('a.spu')
            ->order('skuquantity desc')
            ->paginate($limit);
        $lists = $list->items();
        //批量获取sku图片;
        $spus  = array_column($lists,'spu');

        //批量获取图片地址;
        $product_names= Db::name('product')->field('spu,product_name,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_name_map = array_column($product_names,null,'spu');
        foreach ($lists as $k=>$v) {
            $links                        = self::get_links($v['spu'],$supply_id);
            $lists[$k]['date'] = $date;
            $product_images_product       = $products_name_map[$v['spu']]??[];
            $product_images               = $product_images_product['product_images']??[];
            $display_images               = $product_images ? current(json_decode($product_images)) : '';
            $lists[$k]['product_images']  = $display_images;
            $lists[$k]['supply_links']    = $links;
        }

        $data = [
            'list'  => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }



    /**
     * @desc    获取供应商销量子集数据
     * @date    2024/8/14
     * @author  luckyXiong
     */
    public function get_links($spu='',$supply_id=''){
        if(empty($spu))  return [];
        $where   = [];
        $where[] = ['i.spu','=',$spu];
        $field  = 's.supply_name,i.supply_link';
        if($supply_id){
            $where[] = ['s.id','=',$supply_id];
        }
        return Db::name('supply')
            ->alias('s')
            ->leftJoin('supply_info i', 's.id = i.supply_id')
            ->field($field)
            ->where($where)
            ->group('i.supply_id')
            ->select()
            ->toArray();
    }







    /**
     * @desc    获取供应商销量子集数据
     * @date    2024/7/30
     * @author  luckyXiong
     */
    public function get_info($params=[]){
        $limit = $params['limit'] ?? 10;
        $date  = $params['date']  ?? "";
        $spu   = $params['spu']   ?? "";

        if(!$spu){
            return json(DefaultResponse(201, false, 'spu不能为空!',null));
        }

        $where[]  = ['a.spu', '=', $spu];
        $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

        if (!empty($date)) {
            $date = explode('到',$date);
            $where[] = ['c.createtime', '>=', strtotime($date['0'])];
            $where[] = ['c.createtime', '<=', strtotime($date['1']) + 3600*24-1];
            $date = $date['0'] ."-".date('Y-m-d 23:59:59', strtotime($date['1']));
        }else{
            $yesterday = date('Y-m-d', strtotime('-1 day') - timezone());
            $midnightYesterday = strtotime($yesterday . ' 00:00:00');
            $endOfYesterday  = strtotime($yesterday . ' 23:59:59');
            $where[]  = ['c.createtime', '>=', $midnightYesterday];
            $where[]  = ['c.createtime', '<=', $endOfYesterday];
            $date     = $yesterday ;
        }


        $list = Db::name('order_skuinfo')
            ->field('
                sum(a.realcount) as count,
                a.new_sku as sku
            ')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->where($where)
            ->group('a.new_sku')
            ->order('count desc')
            ->paginate($limit);
        $lists = $list->items();

        //获取供应商;
        $supply_names       = Db::name('supply_info')->field('spu,supply_name,supply_link')->where('spu',$spu)->find();
        $supply_names       = objectToArray($supply_names);
        //批量获取图片信息;
        $seller_skus        = array_column($lists,'sku');
        $seller_skus_images = Db::name('product_inventory')->field('seller_sku,product_images')->whereIn('seller_sku',$seller_skus)->select();
        $seller_skus_images = objectToArray($seller_skus_images);
        $skus_images_map    = array_column($seller_skus_images,null,'seller_sku');
        if($lists){
            foreach($lists as $k=>$v){
                $lists[$k]['date'] = $date;
                $product_images = $skus_images_map[$v['sku']]??[];
                $lists[$k]['product_images'] = $product_images['product_images']??'';
                $lists[$k]['supply_name']    = $supply_names['supply_name']??'';
                $lists[$k]['supply_link']    = $supply_names['supply_link']??'';
            }
        }

        $data = [
            'list'  => $lists,
            'total' => $list->total(),
        ];

        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    /**
     * @desc    获取供应商销量子集数据
     * @date    2025/6/21
     * @author  luckyXiong
     */
    public function getStock($params=[]){
        $limit         = $params['limit'] ?? 100;
        $spu           = $params['spu']   ?? "";
        $supply_id     = $params['supply_id'] ?? "";
        $create_time   = $params['create_time'] ?? "";
        $where         = [];
        $groupId       = $params['groupId'] ?? '';
        $tel           = $params['tel'] ?? '';
        //供应商;2024-10-21
        if($groupId == 18){
            $supply_info   =  Config('Logisticskey.supply_info');
            $supply_id     =  $supply_info[$tel]??'';
        }

        if($spu){
            $where[] = ['spu','=',$spu];
        }

        $supply_name = '';
        if($supply_id){
            //获取该厂家下的所有spu数据
            $supply_name = Db::name('supply')->where('id',$supply_id)->value('supply_name');
            $supply_spus = self::get_supply_spu($supply_id);
            if($supply_spus){
                $where[] = ['spu','in',$supply_spus];
            }
        }

        $list = Db::name('product_stock_sku')
            ->field('id,spu,seller_sku,date_info,supply_id,supply_name,product_name,image_url,create_time,
              sum(nums) as nums,sum(current_nums) as current_nums')
            ->where($where)
            ->group('spu')
            ->order('nums desc')
            ->paginate($limit);
        $lists = $list->items();
        $spus  = array_column($lists,'spu');
        $current_nums_list =  (new OrderLogic())->SalesDetails($spus);
        $current_nums_map  = array_column($current_nums_list,'skuquantity','spu');
         foreach($lists as $k=>$v){
             if($supply_id){
                 $lists[$k]['supply_name'] = $supply_name;
             }
             $current_nums              = $current_nums_map[$v['spu']]??0;
             $lists[$k]['current_nums'] = $current_nums;
         }

        $data  = [
            'list'  => $lists,
            'total' => $list->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    public function get_supply_spu($supply_id){
           $list = Db::name('supply_info')->field('spu')->where(['supply_id'=>$supply_id])->column('spu');
           return $list;
    }



    /**
     * @desc    获取当天的spu详情数据
     * @date    2025/6/21
     * @author  luckyXiong
     */
    public function getSpuStock($params=[]){
        $spu           = $params['spu'] ??"";
        $date          = Db::name('product_stock_sku')->where(['spu'=>$spu])->value('date_info');
        //今天
        $date = date('Y-m-d', time() - timezone());
        $dates         = $date.'到'.$date;
        $info          = (new OrderReportSkuLogic())->skuinfo(['spu'=>$spu,'date'=>$dates]);
        return $info;
    }



    /**
     * @desc    获取当天的spu详情数据---缺货
     * @date    2025/6/21
     * @author  zhangheng
     */
    public function getSpuStockBeOut($params=[]){
        $spu           = $params['spu'] ??"";
        //今天
        // $date = date('Y-m-d', strtotime('-1 day') - timezone());
        $date = date('Y-m-d', time());
        $where[]  = ['spu', '=', $spu]; 
        // $where[] = ['date_info', '=', $date];
        // halt($where);
        
        $lists = Db::name('product_stock_sku')
            ->field('
                sum(nums) as count,
                seller_sku as sku
            ')
            ->where($where)
            ->group('seller_sku')
            ->order('count desc')
            ->select()->toarray();
            
        $colorCounts = [];
        $sizeCounts = [];
        $Counts_Total = 0;
        
        foreach ($lists as $item) { 
            if(empty($item['sku'])){
                continue;
            }
            // 颜色
            list($spu,$color, $size) = explode('-', $item['sku'], 3);  
            
            $spu = trim($spu);
            $color = trim($color);
            $size = trim($size);
            if (!isset($colorCounts[$color])) {  
                $colorCounts[$color] = (int)$item['count'];  
            }else{
                $colorCounts[$color] = $colorCounts[$color] + (int)$item['count'];
            }
            //尺码  
            if (!isset($sizeCounts[$size])) {  
                $sizeCounts[$size] = (int)$item['count'];  
            }else{
                $sizeCounts[$size] = $sizeCounts[$size] + (int)$item['count']; 
            }
            $Counts_Total += (int)$item['count']; 
        }

        $colors = [];
        if(!empty($colorCounts)){
            foreach ($colorCounts as $k=>$v) {
                $Proportion = number_format((float)$v / (float)$Counts_Total*100, 2, '.', '')."%";
                $colors[] = [
                    'name' => $k.":".$v."(".$Proportion.")",  
                    'count' => $v  
                ];  
            }
        }
        

        $sizeCounts_new = [];
        foreach ($sizeCounts as $k=>$v) {
            $sizeCounts_new[] = [
                'size' => $k,
                'count' => $v
            ];
        }
        // halt($sizeCounts_new);
        try{ 
            //针对36E,38E,38D,36D,38F,40E,40F
            usort($sizeCounts_new, function($a, $b) {
                preg_match('/^(\d+)(\w+)$/', $a['size'], $matchesA);
                preg_match('/^(\d+)(\w+)$/', $b['size'], $matchesB);
                $numA = (int)$matchesA[1];
                $charA = $matchesA[2];
                $numB = (int)$matchesB[1];
                $charB = $matchesB[2];
                if ($numA != $numB) {
                    return $numA - $numB;
                }
                return strcmp($charA, $charB);
            });
        } catch (\Exception $e) {
            
        }
        // halt($sizeCounts_new);
        try{
            //针对'XS','S','XS/S','S/M','M','M/L', 'L', 'L/XL', 'XL'
            $sizeCounts_new = (new PlanSuggestLogic())->sort_size($sizeCounts_new);
        } catch (\Exception $e) {
            
        }
        $sizeCounts = array_column($sizeCounts_new, "count", 'size');
        // halt($sizeCounts_new);

        $cups = [];
        if(!empty($sizeCounts)){
            foreach ($sizeCounts as $k=>$v) {
                $Proportion = number_format((float)$v / (float)$Counts_Total*100, 2, '.', '')."%";
                $cups[] = [
                    'name' => $k.":".$v."(".$Proportion.")",  
                    'count' => $v  
                ];
            }
        }

        $data = [
            'spu' => $lists,
            'color' => $colors,
            'cup' => $cups,
        ];
        return $data;
    }



    public function export_need_info($params=[]){
        $header = [];
        $header[] = ['SKU', 'sku'];
        $header[] = ['件数', 'count'];
        $tableName = "need_info";

        
        $spu           = $params['spu'] ??"";
        //今天
        // $date = date('Y-m-d', strtotime('-1 day') - timezone());
        $date = date('Y-m-d', time());
        $where[]  = ['spu', '=', $spu]; 
        // $where[] = ['date_info', '=', $date];
        // halt($where);
        
        $lists = Db::name('product_stock_sku')
            ->field('
                sum(nums) as count,
                seller_sku as sku
            ')
            ->where($where)
            ->group('seller_sku')
            ->order('count desc')
            ->select()->toarray();
            
        $colorCounts = [];
        $sizeCounts = [];
        $Counts_Total = 0;
        foreach ($lists as $item) { 
            if(empty($item['sku'])){
                continue;
            }
            // 颜色
            list($spu,$color, $size) = explode('-', $item['sku'], 3);  
            $spu = trim($spu);
            $color = trim($color);
            $size = trim($size);
            if (!isset($colorCounts[$color])) {  
                $colorCounts[$color] = (int)$item['count'];  
            }else{
                $colorCounts[$color] = $colorCounts[$color] + (int)$item['count'];
            }
            //尺码  
            if (!isset($sizeCounts[$size])) {  
                $sizeCounts[$size] = (int)$item['count'];  
            }else{
                $sizeCounts[$size] = $sizeCounts[$size] + (int)$item['count']; 
            }
            $Counts_Total += (int)$item['count']; 
        }
        

        $header_arr['sku'] = "";
        $header_arr['count'] = "";
        $lists[] = $header_arr;
        $header_arr['sku'] = "颜色";
        $header_arr['count'] = "占比";
        $lists[] = $header_arr;

        if(!empty($colorCounts)){
            foreach ($colorCounts as $k=>$v) {
                $Proportion = number_format((float)$v / (float)$Counts_Total*100, 2, '.', '')."%";
                $lists[] = [
                    'sku' => $k,  
                    'count' => $Proportion,
                ];  
            }
        }

        $header_arr['sku'] = "";
        $header_arr['count'] = "";
        $lists[] = $header_arr;
        $header_arr['sku'] = "尺码";
        $header_arr['count'] = "占比";
        $lists[] = $header_arr;
        
        if(!empty($sizeCounts)){
            foreach ($sizeCounts as $k=>$v) {
                $Proportion = number_format((float)$v / (float)$Counts_Total*100, 2, '.', '')."%";
                $lists[] = [
                    'sku' => $k,  
                    'count' => $Proportion,
                ];
            }
        }

        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }



}